import { SysMenu } from "@/common/domain/sys_menu";
import { db } from "@/common/database/db";

export const SysMenuDao = {
  async list(): Promise<SysMenu[]> {
    return db.selectFrom("sys_menu").selectAll().orderBy('parent_id', 'asc').orderBy("order_num", "asc").execute();
  },
  async getById(menu_id: number): Promise<SysMenu | undefined> {
    return db.selectFrom("sys_menu").selectAll().where("menu_id", "=", menu_id).executeTakeFirst();
  },
  async create(data: Partial<SysMenu>): Promise<any> {
    const result = await db.insertInto("sys_menu").values(data as any).execute();
    return Number((result as any).insertId);
  },
  async update(menu_id: number, data: Partial<SysMenu>): Promise<any> {
    const result = await db.updateTable("sys_menu").set(data as any).where("menu_id", "=", menu_id).execute();
    return Number((result as any).numUpdatedRows);
  },
  async delete(menu_id: number): Promise<any> {
    const result = await db.deleteFrom("sys_menu").where("menu_id", "=", menu_id).execute();
    return Number((result as any).numDeletedRows);
  },

  async listByUserId(user_id: number): Promise<any[]> {
    /**
     select distinct m.menu_id, m.parent_id, m.menu_name, m.path, m.component, m.`query`, m.route_name, m.visible, m.status, ifnull(m.perms,'') as perms, m.is_frame, m.is_cache, m.menu_type, m.icon, m.order_num, m.create_time
		from sys_menu m
			 left join sys_role_menu rm on m.menu_id = rm.menu_id
			 left join sys_user_role ur on rm.role_id = ur.role_id
			 left join sys_role ro on ur.role_id = ro.role_id
			 left join sys_user u on ur.user_id = u.user_id
		where u.user_id = #{userId} and m.menu_type in ('M', 'C') and m.status = 0  AND ro.status = 0
		order by m.parent_id, m.order_num
     */
    const result = await db.selectFrom("sys_menu as m")
      .innerJoin("sys_role_menu as rm", "m.menu_id", "rm.menu_id")
      .innerJoin("sys_user_role as ur", "rm.role_id", "ur.role_id")
      .innerJoin("sys_role as ro", "ur.role_id", "ro.role_id")
      .innerJoin("sys_user as u", "ur.user_id", "u.user_id")
      .select(['m.menu_id', 'm.parent_id', 'm.menu_name', 'm.path', 'm.component', 'm.query', 'm.route_name', 'm.visible', 'm.status', 'm.perms', 'm.is_frame', 'm.is_cache', 'm.menu_type', 'm.icon', 'm.order_num', 'm.create_time'])
      .where("u.user_id", "=", user_id)
      .where("m.menu_type", "in", ['M', 'C'])
      .where("m.status", "=", "0")
      .where("ro.status", "=", "0")
      .orderBy("m.parent_id", "asc")
      .orderBy("m.order_num", "asc")
      .execute(); 
    return result;
  },
  
  async getRolePermissions(roleId: number): Promise<string[]> {
    /*
    select distinct m.perms
    from sys_menu m
       left join sys_role_menu rm on m.menu_id = rm.menu_id
    where m.status = '0' and rm.role_id = #{roleId}
    */
    const result = await db
      .selectFrom('sys_menu as m')
      .innerJoin('sys_role_menu as rm', 'm.menu_id', 'rm.menu_id') // 虽然原SQL是LEFT，但WHERE有rm条件，实际是INNER
      .select('m.perms')
      .where('m.status', '=', '0')
      .where('rm.role_id', '=', roleId) // roleId 是变量
      .distinct()
      .execute();

    // 提取 perms 数组 并过滤null和空字符串
    const perms = result.map(row => row.perms).filter(perm => perm !== null && perm !== '');
    return perms as string[];
  }
}; 